package com.yearner.reviewplan.common.exception;

import com.yearner.reviewplan.common.model.Result;
import com.yearner.reviewplan.user.exceptions.NotLoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletResponse;

/**
 * @author pengyg
 * @since 2019/12/3
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 用户未登录
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public Object notLogin(NotLoginException e) {
        log.debug(e.getMessage());
        return Result.failed(e.getError().getCode(),e.getMessage());
    }

    /**
     * 拦截自定义的运行时异常
     */
    @ExceptionHandler(BaseAppException.class)
    @ResponseBody
    public Object appException(BaseAppException e, HttpServletResponse response) {
        log.debug(e.getMessage());
        response.setStatus(e.getError().getCode());
        return Result.failed(e.getError().getCode(),e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Object runtime(Exception e) {
        log.debug(e.getMessage());
        return Result.failed(e.toString());
    }



}
